package com.netty.io.blockio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author zhangbq
 * @since 2020-12-04 15:39
 * 直接一个线程发起Socket请求，请求到服务端成为一个accept请求，返回作为一个socket去到服务端处理
 **/
public class BioSocketClient {
    public static void main(String[] args) {
        //创建一个Socket，封装所有客户端对服务端的请求数据
        Socket socketClient = null;
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;

        try {
            socketClient = new Socket("localhost", 888);
            //有了socket就可以进行通信了
            bufferedReader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
            //写回到server端的数据
            printWriter = new PrintWriter(socketClient.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("服务端与客户端通信发生异常 ： " + e.getMessage());
        }finally {
            if (null != bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != printWriter){
                printWriter.close();
            }
            //关socket
            if(null != socketClient){
                try {
                    socketClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
